package study.springcloud.client.rest.support.rest;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TraceInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        log.info(">>>>>>>>>> 远程请求");
        //
        Stopwatch stopwatch = Stopwatch.createStarted();

        //uri
        String uri = request.getURI().getPath();
        //header
        HttpHeaders headers = request.getHeaders();
        headers.forEach((k, v) -> {
            //log.info(">>> {}= {}", k, v);
        });
        //method
        String method = request.getMethodValue();
        //log.info(">>> {}", method);
        //body
        if (Objects.equals("POST", method)) {
            //log.info(">>>>>> {}", new String(body));
        }

        //
        ClientHttpResponse response;
        try {
            response = execution.execute(request, body);
        } catch (Exception ex) {
            throw ex;
        } finally {
            log.info("[{}] cost time [{}] ms", uri, stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
        return response;
    }
}
